package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Spinner;

import com.example.myapplication.db.DBManager;
import com.example.myapplication.db.DataManager;
import com.example.myapplication.db.domain.AccountBean;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class ChartIncomeActivity extends AppCompatActivity {
    private ImageView main_bottom_01,
            main_bottom_02,
            main_bottom_03,
            main_bottom_04,
            main_bottom_05;
    List<Entry> list = new ArrayList<>();
    List<PieEntry> list1=new ArrayList<>();
    LineChart line;
    PieChart pie;
    int year,month;
    String in="收入";

    int user_id;

    float [] money=new float[32];
    float [] type_money=new float[5];


    private final String[] typeArray ={"工资","兼职","理财","礼金","其他"
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chart_income);

         line = (LineChart) findViewById(R.id.line);
         pie = (PieChart) findViewById(R.id.pie);
        Spinner year_spinner = findViewById(R.id.spinner_month);
        //类型的选择
        Spinner month_spinner = findViewById(R.id.spinner_year);

        if(DataManager.isLogin){
            user_id = DataManager.userId;
        }

        //        绑定底部导航栏
        main_bottom_01 = findViewById(R.id.main_bottom_01);
        main_bottom_02 = findViewById(R.id.main_bottom_02);
        main_bottom_03 = findViewById(R.id.main_bottom_03);
        main_bottom_04 = findViewById(R.id.main_bottom_04);
        main_bottom_05 = findViewById(R.id.main_bottom_05);

//      导航底部绑定跳转事件
        main_bottom_01.setOnClickListener(view -> {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
        });
        main_bottom_03.setOnClickListener(view -> {
            Intent intent = new Intent(this, addFragment.class);
            startActivity(intent);
        });
        main_bottom_04.setOnClickListener(view -> {
            Intent intent = new Intent(this, FindActivity.class);
            startActivity(intent);
        });
        main_bottom_05.setOnClickListener(view -> {
            Intent intent = new Intent(this, personalPage.class);
            startActivity(intent);
        });
        year_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
                String result = adapterView.getItemAtPosition(position).toString();
                year=Integer.parseInt(result.split("年")[0]);

                List<AccountBean> accountsByMonth = DBManager.findAccountsByMonth(user_id, month, year);
                List<AccountBean> accountsByMonth1=new ArrayList<>();
                if(accountsByMonth!=null){
                    for (int i = 0; i < accountsByMonth.size(); i++) {
                        if(Objects.equals(accountsByMonth.get(i).getIn_out(), "收入")){
                            accountsByMonth1.add(accountsByMonth.get(i));
                        }
                    }
                }
                if(accountsByMonth1!=null){
                    for (int i = 0; i < accountsByMonth1.size(); i++) {
                        for (int j = 1; j < 32; j++) {
                            if(accountsByMonth1.get(i).getDay()==j){
                                money[j]+=accountsByMonth1.get(i).getMoney();
                            }
                        }
                    }
                }
                for (int i = 1; i < 32; i++) {
                    list.add(new Entry(i, money[i]));
                }
                list.add(new Entry(0,0));

                LineDataSet lineDataSet = new LineDataSet(list, "本月每天收入情况");
                LineData lineData = new LineData(lineDataSet);
                //有多条数据则使用adddataset()方法 参数是你的DataSet
                //lineData.addDataSet(lineDataSet);
                line.setData(lineData);

                if(accountsByMonth1!=null){
                    for (int i = 0; i < accountsByMonth1.size(); i++) {
                        for (int j = 0; j < 5; j++) {
                            if(accountsByMonth1.get(i).getType().equals(typeArray[j])){
                                type_money[j]+=accountsByMonth1.get(i).getMoney();
                            }
                        }
                    }
                }

                float total=0;
                for(int i=0;i<5;i++){
                    total+=type_money[i];
                }

                for(int i=0;i<5;i++){
                    if(type_money[i]!=0) {
                        list1.add(new PieEntry(type_money[i] / total, typeArray[i]));
                    }
                }

                //list是你这条线的数据  "销售比例" 是你对这个饼的描述
                PieDataSet PieDataSet = new PieDataSet(list1,"支出类型");
                PieDataSet.setSliceSpace(0f); //设置饼状Item之间的间隙
                PieDataSet.setColors(getResources().getColor(R.color.teal_200), getResources().getColor(R.color.teal_700),
                        getResources().getColor(R.color.blue),getResources().getColor(R.color.gray_111),
                        getResources().getColor(R.color.purple_200),
                        getResources().getColor(R.color.purple_500),getResources().getColor(R.color.purple_700),
                        getResources().getColor(R.color.hehe_blue)); //为DataSet中的数据匹配上颜色集(饼图Item颜色)
                PieData pieData = new PieData(PieDataSet);
                pieData.setDrawValues(true);            //设置是否显示数据实体(百分比，true:以下属性才有意义)
                pieData.setValueTextColor(Color.WHITE);  //设置所有DataSet内数据实体（百分比）的文本颜色
                pieData.setValueTextSize(12f);
                pieData.setValueFormatter(new PercentFormatter());

                pie.setHoleRadius(0);
                pie.setTransparentCircleRadius(0);
                pie.setData(pieData);
                pie.invalidate();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        month_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
                String result = adapterView.getItemAtPosition(position).toString();
                month=Integer.parseInt(result.split("月")[0]);

                List<AccountBean> accountsByMonth = DBManager.findAccountsByMonth(user_id, month, year);
                List<AccountBean> accountsByMonth1=new ArrayList<>();
                if(accountsByMonth!=null){
                    for (int i = 0; i < accountsByMonth.size(); i++) {
                        if(Objects.equals(accountsByMonth.get(i).getIn_out(), "收入")){
                            accountsByMonth1.add(accountsByMonth.get(i));
                        }
                    }
                }
                if(accountsByMonth1!=null){
                    for (int i = 0; i < accountsByMonth1.size(); i++) {
                        for (int j = 1; j < 32; j++) {
                            if(accountsByMonth1.get(i).getDay()==j){
                                money[j]+=accountsByMonth1.get(i).getMoney();
                            }
                        }
                    }
                }
                for (int i = 1; i < 32; i++) {
                    list.add(new Entry(i, money[i]));
                }
                list.add(new Entry(0,0));

                //list是你这条线的数据  "android" 是你对这条线的描述（也就是图例上的文字）
                LineDataSet lineDataSet = new LineDataSet(list, "本月每天收入情况");
                LineData lineData = new LineData(lineDataSet);
                //有多条数据则使用adddataset()方法 参数是你的DataSet
                //lineData.addDataSet(lineDataSet);
                line.setData(lineData);


                if(accountsByMonth1!=null){
                    for (int i = 0; i < accountsByMonth1.size(); i++) {
                        for (int j = 0; j < 5; j++) {
                            if(accountsByMonth1.get(i).getType().equals(typeArray[j])){
                                type_money[j]+=accountsByMonth1.get(i).getMoney();
                            }
                        }
                    }
                }

                float total=0;
                for(int i=0;i<5;i++){
                    total+=type_money[i];
                }

                for(int i=0;i<5;i++){
                    if(type_money[i]!=0) {
                        list1.add(new PieEntry(type_money[i] / total, typeArray[i]));
                    }
                }

                //list是你这条线的数据  "销售比例" 是你对这个饼的描述
                PieDataSet PieDataSet = new PieDataSet(list1, "数据说明");
                PieDataSet.setSliceSpace(0f); //设置饼状Item之间的间隙
                PieDataSet.setColors(getResources().getColor(R.color.teal_200), getResources().getColor(R.color.teal_700),
                        getResources().getColor(R.color.blue),getResources().getColor(R.color.gray_111),
                        getResources().getColor(R.color.purple_200),
                        getResources().getColor(R.color.purple_500),getResources().getColor(R.color.purple_700),
                        getResources().getColor(R.color.hehe_blue)); //为DataSet中的数据匹配上颜色集(饼图Item颜色)
                PieData pieData = new PieData(PieDataSet);
                pieData.setDrawValues(true);            //设置是否显示数据实体(百分比，true:以下属性才有意义)
                pieData.setValueTextColor(Color.WHITE);  //设置所有DataSet内数据实体（百分比）的文本颜色
                pieData.setValueTextSize(12f);
                pieData.setValueFormatter(new PercentFormatter());

                pie.setHoleRadius(0);
                pie.setTransparentCircleRadius(0);
                pie.setData(pieData);

            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        line.setBackgroundColor(Color.WHITE);
        // disable description text
        line.getDescription().setEnabled(false);
        // enable touch gestures
        line.setTouchEnabled(true);
        // enable scaling and dragging
        line.setDragEnabled(true);
        line.setScaleEnabled(true);
        // line.setScaleXEnabled(true);
        // line.setScaleYEnabled(true);
        // force pinch zoom along both axis
        line.setPinchZoom(true);


        PieDataSet PieDataSet = new PieDataSet(list1, "收入类型");
        PieDataSet.setSliceSpace(0f); //设置饼状Item之间的间隙
        PieDataSet.setColors(getResources().getColor(R.color.teal_200), getResources().getColor(R.color.teal_700),
                getResources().getColor(R.color.blue),getResources().getColor(R.color.gray_111),
                getResources().getColor(R.color.purple_200),
                getResources().getColor(R.color.purple_500),getResources().getColor(R.color.purple_700),
                getResources().getColor(R.color.hehe_blue)); //为DataSet中的数据匹配上颜色集(饼图Item颜色)
        PieData pieData = new PieData(PieDataSet);
        pieData.setDrawValues(true);            //设置是否显示数据实体(百分比，true:以下属性才有意义)
        pieData.setValueTextColor(Color.WHITE);  //设置所有DataSet内数据实体（百分比）的文本颜色
        pieData.setValueTextSize(12f);
        pieData.setValueFormatter(new PercentFormatter());

        pie.setHoleRadius(0);
        pie.setTransparentCircleRadius(0);
        pie.setData(pieData);
    }
}